import {CloseCircleOutlined} from '@ant-design/icons';
import {
    FooterToolbar,
    PageContainer,
    ProForm,
    ProFormSelect,
    ProFormText,
    ProFormDigit,
} from '@ant-design/pro-components';
import {Card, Col, message, Popover, Row, Form, InputNumber} from 'antd';
import type {FC} from 'react';
import {useState} from 'react';
import {hostComputerAdd} from './service';
import useStyles from './style.style';
import {useNavigate} from 'react-router-dom';
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {skuSelectList} from "@/pages/power/sku/sku-list/service";

type InternalNamePath = (string | number)[];
const fieldLabels = {
    dataCenterId: '资源池',
    skuId: '规格',
    machineRoomNo: '机房编号', // 机房编号
    cabinetNo: '机柜编号', // 机柜编号
    UPosition: 'U位区间', // U位区间
    hostIp: '主机IP',
    ipoibIp: 'IPoIB IP',
    deviceType: '设备类型',
    systemOS: '系统',
    powerConsumption: '功率',
    loginName: '管理账号',
    loginPassword: '管理密码',
    ipmiIp: 'IPMI IP',
    ipmiIpLoginName: 'IPMI账号',
    ipmiIpLoginPassword: 'IPMI密码',
};

interface ErrorField {
    name: InternalNamePath;
    errors: string[];
}

const HostComputerAddForm: FC<Record<string, any>> = () => {
    const navigate = useNavigate();
    const {styles} = useStyles();
    const [error, setError] = useState<ErrorField[]>([]);
    const getErrorInfo = (errors: ErrorField[]) => {
        const errorCount = errors.filter((item) => item.errors.length > 0).length;
        if (!errors || errorCount === 0) {
            return null;
        }
        const scrollToField = (fieldKey: string) => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
        const errorList = errors.map((err) => {
            if (!err || err.errors.length === 0) {
                return null;
            }
            const key = err.name[0] as 'name' | 'url' | 'owner' | 'approver' | 'dateRange' | 'type';
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <CloseCircleOutlined className={styles.errorIcon}/>
                    <div className={styles.errorMessage}>{err.errors[0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
        <Popover
            title="表单校验信息"
            content={errorList}
            overlayClassName={styles.errorPopover}
            trigger="click"
            getPopupContainer={(trigger: HTMLElement) => {
                if (trigger && trigger.parentNode) {
                    return trigger.parentNode as HTMLElement;
                }
                return trigger;
            }}
        >
          <CloseCircleOutlined/>
        </Popover>
                {errorCount}
      </span>
        );
    };
    const onFinish = async (values: Record<string, any>) => {
        setError([]);
        try {
            await hostComputerAdd(values);
            message.success('提交成功');
            navigate('/power/host-computer/list');
        } catch {
            // console.log
        }
    };
    const onFinishFailed = (errorInfo: any) => {
        setError(errorInfo.errorFields);
    };
    return (
        <ProForm
            layout="vertical"
            submitter={{
                render: (props, dom) => {
                    return (
                        <FooterToolbar>
                            {getErrorInfo(error)}
                            {dom}
                        </FooterToolbar>
                    );
                },
            }}
            initialValues={{}}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
        >
            <PageContainer>
                <Card title="基础信息" className={styles.card} bordered={false}>
                    <Row>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormSelect
                                label={fieldLabels.dataCenterId}
                                name="dataCenterId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择资源池',
                                    },
                                ]}
                                placeholder="请选择资源池"
                                request={async () => {
                                    const res = await dataCenterSelectList({});
                                    return res.data.map((item) => ({
                                        label: item.name,
                                        value: item.dataCenterId,
                                    }));
                                }}
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormSelect
                                label={fieldLabels.skuId}
                                name="skuId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择规格',
                                    },
                                ]}
                                request={async () => {
                                    const res = await skuSelectList({});
                                    return res.data.map((item) => ({
                                        label: item.skuName,
                                        value: item.skuId,
                                    }));
                                }}
                                placeholder="请选择规格"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 6,
                            }}
                            md={{
                                span: 24,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.deviceType}
                                name="deviceType"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入设备类型信息',
                                    },
                                ]}
                                placeholder="请输入设备类型信息"
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormText
                                label={fieldLabels.machineRoomNo}
                                name="machineRoomNo"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入信息',
                                    },
                                ]}
                                placeholder="请输入信息"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.cabinetNo}
                                name="cabinetNo"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入信息',
                                    },
                                ]}
                                placeholder="请输入信息"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 6,
                            }}
                            md={{
                                span: 24,
                            }}
                            sm={24}
                        >
                            <Form.Item label={fieldLabels.UPosition} style={{marginBottom: 0}}>
                                <Form.Item
                                    name="uPositionStart"
                                    rules={[{required: true}]}
                                    style={{display: 'inline-block', width: 'calc(40% - 8px)'}}
                                >
                                    <InputNumber addonAfter="U" placeholder="开始区间"/>
                                </Form.Item>
                                -
                                <Form.Item
                                    name="uPositionEnd"
                                    rules={[{required: true}]}
                                    style={{display: 'inline-block', width: 'calc(40% - 8px)', margin: '0 8px'}}
                                >
                                    <InputNumber addonAfter="U" placeholder="结束区间"/>
                                </Form.Item>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormText
                                label={fieldLabels.systemOS}
                                name="systemOS"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入系统信息',
                                    },
                                ]}
                                placeholder="请输入系统信息"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormDigit
                                label={fieldLabels.powerConsumption}
                                name="powerConsumption"
                                fieldProps={{
                                    addonAfter: "W",
                                    precision: 0
                                }}
                                placeholder="请输入功耗信息"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 6,
                            }}
                            md={{
                                span: 24,
                            }}
                            sm={24}
                        >

                        </Col>
                    </Row>
                </Card>
                <Card title="连接信息" className={styles.card} bordered={false}>
                    <Row gutter={16}>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormText
                                label={fieldLabels.hostIp}
                                name="hostIp"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入主机IP',
                                    },
                                ]}
                                placeholder="请输入主机IP"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.loginName}
                                name="loginName"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入管理账号',
                                    },
                                ]}
                                placeholder="请输入管理账号"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 6,
                            }}
                            md={{
                                span: 24,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.loginPassword}
                                name="loginPassword"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入管理密码',
                                    },
                                ]}
                                placeholder="请输入管理密码"
                            />
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormText
                                label={fieldLabels.ipmiIp}
                                name="ipmiIp"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入',
                                    },
                                ]}
                                placeholder="请输入"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.ipmiIpLoginName}
                                name="ipmiIpLoginName"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入信息',
                                    },
                                ]}
                                placeholder="请输入信息"
                            />
                        </Col>
                        <Col
                            xl={{
                                span: 6,
                                offset: 2,
                            }}
                            lg={{
                                span: 8,
                            }}
                            md={{
                                span: 12,
                            }}
                            sm={24}
                        >
                            <ProFormText
                                label={fieldLabels.ipmiIpLoginPassword}
                                name="ipmiIpLoginPassword"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入信息',
                                    },
                                ]}
                                placeholder="请输入信息"
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col lg={6} md={12} sm={24}>
                            <ProFormText
                                label={fieldLabels.ipoibIp}
                                name="ipoibIp"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入信息',
                                    },
                                ]}
                                placeholder="请输入信息"
                            />
                        </Col>
                    </Row>
                </Card>
            </PageContainer>
        </ProForm>
    );
};
export default HostComputerAddForm;
